package com.yuzhantao.collection.sensorflow;

import javax.annotation.PreDestroy;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Service.Listener;
import com.google.common.util.concurrent.Service.State;
import com.yuzhantao.collection.sensorflow.service.PushCollectionCommandOfUInfoService;
import com.yuzhantao.collection.sensorflow.service.PushTemperatureService;
import com.yuzhantao.collection.sensorflow.service.UInfoRegularlyReportService;

/**
 * SensorFlow相关服务管理
 * @author yuzhantao
 *
 */
@Service
public class SensorFlowServiceManager implements ApplicationRunner {
	protected final static Logger logger = Logger.getLogger(SensorFlowServiceManager.class);
	@Autowired
	UInfoRegularlyReportService uService;
	
	@Autowired
	PushCollectionCommandOfUInfoService pushCollectionCommandOfUInfoService;
	
	@Autowired
	PushTemperatureService pushTemperatureService;
	
	private void runService() {
//		uService.addListener(new Listener() {
//
//			@Override
//			public void starting() {
//				logger.info("U位信息上报服务开始启动......");
//			}
//
//			@Override
//			public void running() {
//				logger.info("U位信息上报服务开始运行");
//			}
//
//			@Override
//			public void stopping(State from) {
//				logger.info("U位信息上报服务关闭中");
//			}
//
//			@Override
//			public void terminated(State from) {
//				logger.info("U位信息上报服务终止");
//			}
//
//			@Override
//			public void failed(State from, Throwable failure) {
//				logger.info("U位信息上报服务失败:" + failure.getCause());
//			}
//
//		}, MoreExecutors.directExecutor());
//
//		uService.startAsync().awaitRunning();

		pushTemperatureService.addListener(new Listener() {

			@Override
			public void starting() {
				logger.info("推送温度服务开始启动......");
			}

			@Override
			public void running() {
				logger.info("推送温度服务开始运行");
			}

			@Override
			public void stopping(State from) {
				logger.info("推送温度服务关闭中");
			}

			@Override
			public void terminated(State from) {
				logger.info("推送温度服务终止");
			}

			@Override
			public void failed(State from, Throwable failure) {
				logger.info("推送温度服务失败:" + failure.getCause());
			}
			
		}, MoreExecutors.directExecutor());
		pushTemperatureService.startAsync().awaitRunning();
	}
	
	@PreDestroy
	public void destory() {
		if(uService!=null) {
			uService.stopAsync().awaitTerminated();
		}
		
		if(pushCollectionCommandOfUInfoService!=null) {
			pushCollectionCommandOfUInfoService.stopAsync().awaitTerminated();
		}
		
		if(pushTemperatureService!=null) {
			pushTemperatureService.stopAsync().awaitTerminated();
		}
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		this.runService();
	}
	
}
